﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NAudio.Wave;

namespace STT_Test_Plus.ViewModels;

public partial class MainWindowViewModel : ViewModelBase
{
#pragma warning disable CA1822 // Mark members as static
    public string Greeting => "Welcome to Avalonia!";
#pragma warning restore CA1822 // Mark members as static
    
    /// <summary>
    /// 开始录音，返回录音保存的文件
    /// </summary>
    /// <param name="token">停止录音的令牌</param>
    /// <returns></returns>
    public static async Task<string> Record(CancellationToken token)
    {
        var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMdd_HHmmss.wav"));
        var waveIn = new WaveInEvent() { WaveFormat = new WaveFormat(16000, 16, 1) };
        var writer = new WaveFileWriter(fileName, waveIn.WaveFormat);
        waveIn.StartRecording();
        waveIn.DataAvailable +=async (s, e) =>await writer.WriteAsync(e.Buffer, 0, e.BytesRecorded);
        waveIn.RecordingStopped += (s, e) =>
        {
            writer.Dispose();
            writer = null;
            waveIn.Dispose();
        };
        while (true)
        {
            try
            {
                await Task.Delay(1000, token);
            }
            catch (Exception e)
            {
               
            }
            
            if (token.IsCancellationRequested)
            {
                waveIn.StopRecording();
                await Task.Delay(500);
                break;
            }
        }
        return fileName;
    } 
}